#
# script.wold - XBMC Wake on LAN daemon
#
# Copyright (C) 2012 Adam Sutton <dev@adamsutton.me.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# ############################################################################
# Module Setup/Info
# #############################################################################

# Global imports
import os, sys, time
import xbmcaddon

# Addon info
__addon__     = xbmcaddon.Addon()                 
__addonname__ = __addon__.getAddonInfo('name')
__cwd__       = __addon__.getAddonInfo('path')
__author__    = __addon__.getAddonInfo('author')
__version__   = __addon__.getAddonInfo('version')
__language__  = __addon__.getLocalizedString
sys.path.append(xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib')))

# Local imports
import wol

# Defaults
PERIOD = 5.0

# ############################################################################
# Functions
# #############################################################################

#
# Logging (TODO: move)
#
def log ( msg ):
  xbmc.log('%s - %s' % (__addonname__, msg))

#
# Wait period
#
def wait_period ( period ):
  period = min(period, PERIOD)
  time.sleep(period)

#
# Wait for input
#
def wait_input ( num ):
  if num  < 0: num = 0
  event = '/dev/input/event%d' % num

  # Open
  (ip_pd, ip_fd) = wol.input_setup(event)
  if not ip_fd or not ip_pd: raise Exception('invalid device')
  
  # Wait
  return wol.input_ready(ip_pd, PERIOD)

# ############################################################################
# Main
# #############################################################################
  
# Addon started
log('started')
log('author:  %s' % __author__)
log('version: %s' % __version__)

# State
wake = True
last = None
ok   = True

# Until terminated
while ok and not xbmc.abortRequested:

  try:
    now = time.time()

    # Get MACs
    macs   = []
    for i in range(3):
      m = __addon__.getSetting('mac%d' % i).upper()
      if wol.is_mac(m): macs.append(m)

    # Send wakeup
    if wake:
      last   = now
      port   = int(__addon__.getSetting('port'))
      repeat = int(__addon__.getSetting('repeat'))
      if repeat < 1: repeat = 1
      for m in macs:
        log('send to %s' % m)
        wol.send(m, port, repeat)

    # Reset
    wake = False
    mode = __addon__.getSetting('mode')

    # Periodic
    if mode == 'period':
      period = float(__addon__.getSetting('period'))
      wait_period(period)
      if (now - last) >= period:
        wake = True
  
    # Remote
    elif mode == 'remote':
      event = int(__addon__.getSetting('event'))
      if wait_input(event): wake = True

    # Startup
    elif mode == 'startup':
      time.sleep(PERIOD)

    # Terminate
    else:
      log('invalid mode %s' % mode)
      ok = False    
  
  # Log it
  except Exception, e:
    log('ERROR: %s' % e)
    time.sleep(PERIOD) # always wait minimum time
    # terminate?

# Terminated
log('exiting')
